package com.alexgaoyh.MutiModule.Dubbo.RWSeperate.consumer.web.manager.sysman.sysmanResource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import com.MutiModule.common.exception.MyLogicException;
import com.MutiModule.common.exception.MyNumberFormatException;
import com.MutiModule.common.twitter.IDGenerator.instance.IdWorkerInstance;
import com.MutiModule.common.utils.DateUtils;
import com.MutiModule.common.utils.JSONUtilss;
import com.MutiModule.common.utils.StringUtilss;
import com.MutiModule.common.vo.TreeNode;
import com.MutiModule.common.vo.ZTreeNodes;
import com.MutiModule.common.vo.enums.DeleteFlagEnum;
import com.MutiModule.common.vo.enums.MenuResourceTypeEnum;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.sysman.sysmanResource.read.ISysmanResourceReadService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.sysman.sysmanResource.write.ISysmanResourceWriteService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.consumer.web.base.BaseController;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.sysman.sysmanResource.SysmanResource;
import com.alibaba.dubbo.config.annotation.Reference;

/**
*
* dubbo 消费者
 * SysmanResource 模块 读接口
 * @author alexgaoyh
*
*/
@Controller
@RequestMapping(value="manager/sysman/sysmanResource")
public class SysmanResourceController extends BaseController<SysmanResource>{

	@Reference(group="readService", interfaceName="com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.sysman.sysmanResource.read.ISysmanResourceReadService")
	private ISysmanResourceReadService readService;
	
	@Reference(group="writeService", interfaceName="com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.sysman.sysmanResource.write.ISysmanResourceWriteService")
	private ISysmanResourceWriteService writeService;
	
	@Override
	public ModelAndView list(ModelAndView model, HttpServletRequest request) {
		
		super.list(model, request);
		
		List<TreeNode> treeNodeList = decorateCondition(request);

		model.addObject("treeNodeList", treeNodeList);
		
		model.addObject("menuResourceTypeEnumValues", MenuResourceTypeEnum.values());
		
		String id = request.getParameter("id");
		model.addObject("id", id);
		
		return model;
		
	}
	
	/**
	 * 封装参数部分
	 * @param request
	 * @return
	 */
	protected List<TreeNode> decorateCondition(HttpServletRequest request) {
		
		List<SysmanResource> _rootList = readService.selectSysmanResourceListByNullParentId();
		
		List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
		
		for(SysmanResource _node : _rootList) {
			List<TreeNode> pageView = readService.selectTreeNodeBySysmanResourceId(_node.getId());
			treeNodeList.addAll(pageView);
		}
		
		return treeNodeList;
	}
	
	@Override
	public ModelAndView show(@PathVariable("id") String id, ModelAndView model, HttpServletRequest request, RedirectAttributesModelMap modelMap) throws Exception  {
		
		super.show(id, model, request, modelMap);
		
		SysmanResource entity = readService.selectByPrimaryKey(id);
		model.addObject("entity", entity);
		
		List<ZTreeNodes> list = readService.selectAllResourceZTreeNode();
		model.addObject("zTreeListJSON", JSONUtilss.toJSon(list));
		
		model.addObject("menuResourceTypeEnumValues", MenuResourceTypeEnum.values());
		
		return model;
	}
	
	@Override
	public ModelAndView edit(@PathVariable("id") String id, ModelAndView model, HttpServletRequest request, RedirectAttributesModelMap modelMap) throws Exception  {
		
		super.edit(id, model, request, modelMap);
		
		SysmanResource entity = readService.selectByPrimaryKey(id);
		model.addObject("entity", entity);
		
		List<ZTreeNodes> list = readService.selectAllResourceZTreeNode();
		for(ZTreeNodes _zTree : list) {
			if(entity.getParentId() != null) {
				if(_zTree.getId() + "" == entity.getParentId()) {
					_zTree.setChecked(true);
				}
			}
		}
		model.addObject("zTreeListJSON", JSONUtilss.toJSon(list));
		
		model.addObject("menuResourceTypeEnumValues", MenuResourceTypeEnum.values());
		
		return model;
	}
	
	@Override
	public ModelAndView add(ModelAndView model, HttpServletRequest request) {
		super.add(model, request);
		
		List<ZTreeNodes> list = readService.selectAllResourceZTreeNode();
		model.addObject("zTreeListJSON", JSONUtilss.toJSon(list));
		
		model.addObject("menuResourceTypeEnumValues", MenuResourceTypeEnum.values());
		
		return model;
	}
	
	@Override
	public ModelAndView doSave(ModelAndView model, HttpServletRequest request, SysmanResource entity, RedirectAttributesModelMap modelMap)
			throws Exception {
		super.doSave(model, request, entity, modelMap);
		
		beforeDoSave(request, entity);
		if(StringUtilss.isEmpty(entity.getParentId()) || entity.getParentId().equals("-1")) {
			entity.setParentId(null);
			entity.setLevels(0);
			entity.setParentIds(null);
		}
		writeService.insert(entity);
		afterDoSave(request, entity);
		
		modelMap.addAttribute("id", entity.getId());
		
		model.setViewName("redirect:list");

		return model;
	}
	
	/**
	 * 调用保存方法之前进行的方法调用
	 * @param request
	 * @param entity 对应实体信息
	 * @throws Exception
	 */
	protected void beforeDoSave(HttpServletRequest request, SysmanResource entity) throws Exception {
		String id = IdWorkerInstance.getIdStr();
		
		entity.setId(id);
		entity.setDeleteFlag(DeleteFlagEnum.NORMAL);
		entity.setCreateTime(DateUtils.getGMTBasicTime());
		
		//parentIds list集合
		List<String> _list = new ArrayList<String>();
		if(entity.getParentId() != null) {
			// 按钮级别的功能权限下，不能再存在按钮功能；
			SysmanResource _parentResourceEntity = readService.selectByPrimaryKey(entity.getParentId());
			if(_parentResourceEntity != null && _parentResourceEntity.getResourceType() == MenuResourceTypeEnum.BUTTON ) {
				throw new MyLogicException("按钮级别的功能权限下不能再存在子功能！请确定后重新操作");
			}
			
			_list.add(entity.getParentId());
		}
		_list = readService.selectParentIdsByPrimaryKey(entity.getParentId(), _list);
		
		if(_list.size() > 3) {
			throw new MyNumberFormatException("后台资源管理-不能超过四层结构");
		} else {
			entity.setLevels(_list.size());
			entity.setParentIds(StringUtilss.getStringSeparatorByList(_list, ","));
		}
		
	}
	
	/**
	 * 电泳保存方法之后进行的方法调用
	 * @param request
	 * @param entity 对应实体信息
	 * @throws Exception
	 */
	protected void afterDoSave(HttpServletRequest request, SysmanResource entity) throws Exception {
		
	}
	
	@Override
	public ModelAndView doUpdate(ModelAndView model, HttpServletRequest request, SysmanResource entity, RedirectAttributesModelMap modelMap) throws Exception {
		super.doUpdate(model, request, entity, modelMap);
		
		beforeDoUpdate(request, entity);
		if(StringUtilss.isEmpty(entity.getParentId()) || entity.getParentId().equals("-1")) {
			entity.setParentId(null);
			entity.setLevels(0);
			entity.setParentIds(null);
		}
		writeService.updateByPrimaryKey(entity);
		afterDoUpdate(request, entity);
		
		modelMap.addAttribute("id", entity.getId());
		
		model.setViewName("redirect:list");

		return model;
	}
	
	/**
	 * 调用更新操作之前进行的操作
	 * @param request
	 * @param entity
	 * @throws Exception
	 */
	protected void beforeDoUpdate(HttpServletRequest request, SysmanResource entity) throws Exception {
		
		List<String> _list = new ArrayList<String>();
		// 有可能存在更新过程中操作的节点 原本就不是底层的非叶子节点，还有其他节点在这个节点下面 这个时候的话，则需要把这一部分节点的子节点也加进来
		_list = readService.selectParentIdsByPrimaryKey(entity.getId(), _list);
		
		_list.add(entity.getParentId());
		_list = readService.selectParentIdsByPrimaryKey(entity.getParentId(), _list);
		
		// 更新操作的时候，注意如果更新的节点原先就有部分子节点的话，通用需要将这一部分子节点的参数考虑；
		// 注意这里查询出来的曾经深度包含叶子节点部分的参数
		int maxDepth = readService.selectMaxDepthFromSelectedNodeToLeaf(entity.getId());
		
		if((_list.size() + maxDepth -1) > 3) {
			throw new MyNumberFormatException("后台资源管理-不能超过四层结构");
		} else {
			entity.setLevels(_list.size());
			entity.setParentIds(StringUtilss.getStringSeparatorByList(_list, ","));
		}
	}
	
	/**
	 * 调用更新操作之后进行的操作
	 * @param request
	 * @param entity
	 * @throws Exception
	 */
	protected void afterDoUpdate(HttpServletRequest request, SysmanResource entity) throws Exception {
		
	}

}
